package com.app.base.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.app.base.adapter.viewholder.RVHolder;
import com.app.base.adapter.viewholder.ViewHolder;

import java.util.List;

/**
 * Created by HJ on 2016/4/12 0012.
 * RecyclerView适配器基类
 */
public abstract class RecyclerBaseAdapter<T> extends RecyclerView.Adapter<RVHolder> {


    public List<T> list;

    public Context context;

    public RecyclerBaseAdapter(Context context, List<T> list) {
        this.list = list;
        this.context = context;
    }

    public void addAll(List<T> list) {
        if (list != null) {
            this.list.addAll(list);
            notifyDataSetChanged();
        }
    }

    public void updateData(List<T> list) {
        if(this.list == list) {
            notifyDataSetChanged();
        } else {
            this.list.clear();
            addAll(list);
        }
    }
    @Override
    public RVHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(onCreateViewLayoutID(viewType), parent, false);
        return new RVHolder(view);
    }

    @Override
    public void onViewRecycled(final RVHolder holder) {
        super.onViewRecycled(holder);
    }

    @Override
    public void onBindViewHolder(final RVHolder holder, final int position) {

        onBindViewHolder(holder.getViewHolder(), position);
        final int pos = position;
        if (clickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(clickListener != null) {
                        clickListener.onItemClick(holder.itemView, pos);
                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public abstract int onCreateViewLayoutID(int viewType);

    public abstract void onBindViewHolder(ViewHolder holder, int position);

    protected OnItemClickListener clickListener;

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.clickListener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }
}
